package com.jinlia.show.common.web.config;

import com.alibaba.fastjson.JSONObject;
import com.jinlia.show.common.core.exception.MyRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

@Slf4j
@Component
@RestControllerAdvice
public class RestControllerAdviceConfig {


    /**
     * 其他未知异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<JSONObject> businessExceptionHandler(Exception e) {
        log.error("Exception", e);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("errCode", 600);
        jsonObject.put("errMsg", e.getMessage());
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(jsonObject);
    }

    @ExceptionHandler(value = RuntimeException.class)
    public ResponseEntity<JSONObject> runtimeExceptionHandler(RuntimeException e) {
        JSONObject jsonObject = new JSONObject();
        /**
         * 自定义异常被处理的情况
         */
        Throwable eCauseLink = e;
        while (Objects.nonNull(eCauseLink)) {
            if (eCauseLink instanceof MyRuntimeException) {
                log.error("RuntimeException", e);
                jsonObject.put("errCode", ((MyRuntimeException) eCauseLink).getErrCode());
                jsonObject.put("errMsg", ((MyRuntimeException) eCauseLink).getErrMsg());
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(jsonObject);
            }
            eCauseLink = eCauseLink.getCause();
        }
        log.error("RuntimeException", e);
        log.error("info = {}", e);
        jsonObject.put("errCode", 600);
        jsonObject.put("errMsg", e.getMessage());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(jsonObject);
    }

    @ExceptionHandler(value = MyRuntimeException.class)
    public ResponseEntity<JSONObject> runtimeExceptionHandler(MyRuntimeException e) {
        log.error("MyRuntimeException::", e);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("errCode", e.getErrCode());
        jsonObject.put("errMsg", e.getErrMsg());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(jsonObject);
    }

}
